#include "ClkInitHelper.h"

// 初始化rt
#include <rthw.h>
#include <rtthread.h>

//Clock Config
// 使用内部高速时钟
// 注意，修改频率还需要修改system_hc32f4a0.h中的XTAL_VALUE
// 有源高速晶振需要修改stcXtalInit.u8Mode = CLK_XTAL_MD_OSC;为stcXtalInit.u8Mode = CLK_XTAL_MD_EXCLK;

// 使用外部高速有源时钟
void App_ClkCfg(void)
{
/* Set bus clock div. */
    CLK_SetClockDiv(CLK_BUS_CLK_ALL, (CLK_HCLK_DIV1 | CLK_EXCLK_DIV2 | CLK_PCLK0_DIV1 | CLK_PCLK1_DIV2 | \
                                   CLK_PCLK2_DIV4 | CLK_PCLK3_DIV4 | CLK_PCLK4_DIV2));
    /* sram init include read/write wait cycle setting */
    SRAM_SetWaitCycle(SRAM_SRAM_ALL, SRAM_WAIT_CYCLE1, SRAM_WAIT_CYCLE1);
    SRAM_SetWaitCycle(SRAM_SRAMH, SRAM_WAIT_CYCLE0, SRAM_WAIT_CYCLE0);
    /* flash read wait cycle setting */
    EFM_SetWaitCycle(EFM_WAIT_CYCLE5);
    /* XTAL config */
    stc_clock_xtal_init_t stcXtalInit;
    (void)CLK_XtalStructInit(&stcXtalInit);
    stcXtalInit.u8State = CLK_XTAL_ON;
    stcXtalInit.u8Drv = CLK_XTAL_DRV_HIGH;
    stcXtalInit.u8Mode = CLK_XTAL_MD_EXCLK;
    stcXtalInit.u8StableTime = CLK_XTAL_STB_2MS;
    (void)CLK_XtalInit(&stcXtalInit);
    /* PLLH config */
    stc_clock_pll_init_t stcPLLHInit;
    (void)CLK_PLLStructInit(&stcPLLHInit);
    stcPLLHInit.PLLCFGR = 0UL;
    stcPLLHInit.PLLCFGR_f.PLLM = (1UL - 1UL);
    stcPLLHInit.PLLCFGR_f.PLLN = (48UL - 1UL);
    stcPLLHInit.PLLCFGR_f.PLLP = (5UL - 1UL);
    stcPLLHInit.PLLCFGR_f.PLLQ = (10UL - 1UL);
    stcPLLHInit.PLLCFGR_f.PLLR = (16UL - 1UL);
    stcPLLHInit.u8PLLState = CLK_PLL_ON;
    stcPLLHInit.PLLCFGR_f.PLLSRC = CLK_PLL_SRC_XTAL;
    (void)CLK_PLLInit(&stcPLLHInit);
    /* PLLA config */
    stc_clock_pllx_init_t stcPLLAInit;
    (void)CLK_PLLxStructInit(&stcPLLAInit);
    stcPLLAInit.PLLCFGR = 0UL;
    stcPLLAInit.PLLCFGR_f.PLLM = (5UL - 1UL);
    stcPLLAInit.PLLCFGR_f.PLLN = (48UL - 1UL);
    stcPLLAInit.PLLCFGR_f.PLLP = (16UL - 1UL);
    stcPLLAInit.PLLCFGR_f.PLLQ = (16UL - 1UL);
    stcPLLAInit.PLLCFGR_f.PLLR = (5UL - 1UL);
    stcPLLAInit.u8PLLState = CLK_PLLX_ON;
    (void)CLK_PLLxInit(&stcPLLAInit);
    /* 4 cycles for 200MHz ~ 250MHz */
    GPIO_SetReadWaitCycle(GPIO_RD_WAIT4);
    /* Set the system clock source */
    CLK_SetSysClockSrc(CLK_SYSCLK_SRC_PLL);
}

// rt的tick处理函数。原本在board.c中，本处被移动到此
void rt_os_tick_callback(void)
{
    rt_interrupt_enter();
    
    rt_tick_increase();

    rt_interrupt_leave();
}

/**
 * @brief  SysTick interrupt handler function.
 * @param  None
 * @retval None
 */
void SysTick_Handler(void)
{
	  // 初始化rt的tick
		rt_os_tick_callback();
//    SysTick_IncTick();

//    __DSB();  /* Arm Errata 838869 */
}
